package com.efeichong.common.security;

import com.efeichong.common.domain.entity.redis.LoginUser;
import com.efeichong.common.exception.LoginExpiredException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author lxk
 * @date 2020/11/20
 * @description 返回当前登录的对象
 */
public class LoginContextHolder {
    /**
     * 返回当前登录用户对象
     *
     * @return
     */
    public static LoginUser getLoginUserOrElseThrow() throws LoginExpiredException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new LoginExpiredException();
        } else {
            return (LoginUser) authentication.getPrincipal();
        }
    }

    public static LoginUser getLoginUser() throws LoginExpiredException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        } else {
            return (LoginUser) authentication.getPrincipal();
        }
    }

}
